//
//  JEHDetailViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/9.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHDetailViewController.h"

@interface JEHDetailViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UILabel *introLabel;
@property (nonatomic, retain) UILabel *pageNumLabel;
@property (nonatomic, retain) JEHDataBaseHandle *handle;

@end

@implementation JEHDetailViewController

#pragma mark - memoryManagement
- (void)dealloc {
    
    [_collectionView release];
    [_titleLabel release];
    [_introLabel release];
    [_pageNumLabel release];
    [_handle release];
    [_rootModel release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    [self createCollectionView];
    [self createHeaderView];
    [self createFooterView];
}

#pragma mark - reSetterMethod
- (void)setRootModel:(JEHRootModel *)rootModel {
    if (_rootModel != rootModel) {
        [_rootModel release];
        _rootModel = [rootModel retain];
        [self.collectionView reloadData];
    }
}

#pragma mark - createHeaderView
- (void)createHeaderView {
    
    UIButton *goBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [goBack setImage:[UIImage imageNamed:@"goBackButton"] forState:UIControlStateNormal];
    goBack.frame = CGRectMake(10, 20, 60, kHeaderHeight);
    [goBack addTarget:self action:@selector(goBackAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:goBack];
    
    UIButton *mood = [UIButton buttonWithType:UIButtonTypeCustom];
    [mood setImage:[UIImage imageNamed:@"un_selectMood"] forState:UIControlStateNormal];
    mood.frame = CGRectMake(self.view.width - 190, 20, 60, kHeaderHeight);
    [mood addTarget:self action:@selector(moodAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mood];
    
    UIButton *collect = [UIButton buttonWithType:UIButtonTypeCustom];
    collect.frame = CGRectMake(self.view.width - 130, 20, 60, kHeaderHeight);
    [collect addTarget:self action:@selector(collectedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collect];
    
    self.handle = [JEHDataBaseHandle shareDataBaseHandle];
    [self.handle openDataBase];
    JEHCollectionModel *collectionModel = [self.handle selectWithTitle:self.rootModel.title];
    [self.handle closeDataBase];
    if (![collectionModel.title isEqualToString:_rootModel.title]) {
        [collect setImage:[UIImage imageNamed:@"un_selectCollected"] forState:UIControlStateNormal];
    } else {
        [collect setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
    }
    
    UIButton *share = [UIButton buttonWithType:UIButtonTypeCustom];
    share.frame = CGRectMake(self.view.width - 70, 20, 60, kHeaderHeight);
    [share setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:share];
}

- (void)goBackAction:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

static BOOL isSelect1 = NO;

- (void)moodAction:(UIButton *)sender {
    
    if (isSelect1) {
        
        [sender setImage:[UIImage imageNamed:@"un_selectMood"] forState:UIControlStateNormal];
        isSelect1 = NO;
    } else {
        [sender setImage:[UIImage imageNamed:@"mood"] forState:UIControlStateNormal];
        isSelect1 = YES;
    }
}

- (void)collectedAction:(UIButton *)sender {
    
    if (_rootModel) {

        [self.handle openDataBase];
        JEHCollectionModel *collectionModel = [self.handle selectWithTitle:self.rootModel.title];
        if (![collectionModel.title isEqualToString:_rootModel.title]) {

            collectionModel.title = _rootModel.title;
            collectionModel.category = _rootModel.category;
            collectionModel.link = _rootModel.link;
            [self.handle insertIntoDataBase:collectionModel];
            [self.handle closeDataBase];
            [sender setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alert show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [alert dismissWithClickedButtonIndex:0 animated:NO];
            });
            [alert release];
        } else {
            [self.handle deleteFromDataBase:_rootModel.title];
            [self.handle closeDataBase];
            [sender setImage:[UIImage imageNamed:@"un_selectCollected"] forState:UIControlStateNormal];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消收藏成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alert show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [alert dismissWithClickedButtonIndex:0 animated:NO];
            });
            [alert release];
        }
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"collectionReloadData" object:nil];
    }
}

#pragma mark - share
- (void)shareAction:(UIButton *)sender {
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"566fbfa9e0f55a1273002780" shareText:self.rootModel.url shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, nil] delegate:nil];
}

#pragma mark - createFooterView
- (void)createFooterView {
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 44 - 5, self.view.width, 44 + 5)];
    footerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:footerView];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.view.height / 2 + 130, self.view.width - 20, 30)];
    [_titleLabel release];
    _titleLabel.textColor = [UIColor whiteColor];
    
    self.introLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _titleLabel.bottom, self.view.width - 20, self.view.height / 2 - 130 - 30)];
    [_introLabel release];
    _introLabel.numberOfLines = 0;
    _introLabel.font = [UIFont systemFontOfSize:12];
    _introLabel.textColor = [UIColor whiteColor];
    
    self.pageNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width - 50, self.view.height / 2 + 130, 40, 30)];
    [_pageNumLabel release];
    _pageNumLabel.textColor = [UIColor whiteColor];
    
    [self.view addSubview:_titleLabel];
    [self.view addSubview:_introLabel];
    [self.view addSubview:_pageNumLabel];
}

- (CGFloat)getHeightWithText:(NSString *)text withFont:(CGFloat)font {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
    CGRect rect = [text boundingRectWithSize:CGSizeMake(self.view.width - 20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

#pragma mark - createCollectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 10;
    layout.itemSize = CGSizeMake(self.view.width - 10, self.view.height / 2 + 50);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, self.view.width, self.view.height / 2 + 50) collectionViewLayout:layout];
    [_collectionView release];
    [layout release];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.bounces = NO;
    [_collectionView registerClass:[JEHDetailCollectionViewCell class] forCellWithReuseIdentifier:@"JEHDetailCollectionViewCellIdentifier"];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellIdentifier"];
    [self.view addSubview:_collectionView];
}

#pragma mark - UICollectionViewDelegateMethod
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (_rootModel) {
        
        return self.rootModel.picsModel.listArray.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_rootModel) {

        if (indexPath.item < self.rootModel.picsModel.listArray.count) {
            
            JEHDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JEHDetailCollectionViewCellIdentifier" forIndexPath:indexPath];
            cell.secondModel = self.rootModel.picsModel.listArray[indexPath.item];
            self.titleLabel.text = _rootModel.title;
            self.introLabel.text = _rootModel.intro;
            CGFloat introHeight = [self getHeightWithText:_rootModel.intro withFont:12];
            _introLabel.frame = CGRectMake(10, _titleLabel.bottom, self.view.width - 20, introHeight + 12);
            self.pageNumLabel.text = [NSString stringWithFormat:@"%ld/%ld", indexPath.item + 1, _rootModel.picsModel.listArray.count];
            return cell;
        }
    }
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellIdentifier" forIndexPath:indexPath];
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
